import React, { Component } from 'react';
import { Form, Input, Modal, Checkbox, Radio } from 'antd';
import './role.less';
import * as sysApi from 'common/api/SysApi.js';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

/**
 * 编辑角色页面
 */
class Role extends Component{
	
	constructor(props) {
	    super(props);
	    this.state = {
			roleList: [],
	    }
	}
	
	componentDidMount() {
		this.fetch(this.props.id);
	}
	
	componentWillReceiveProps(nextProps) {
		if(this.props.id != nextProps.id){
			this.fetch(nextProps.id);
		}
	}
	
	//请求数据
	fetch = (id) => {
		this.props.form.setFieldsValue({
			userId: id,
			roleIds: ""
		});
		if(id){
			sysApi.sysUserRoleList({
				userId: id
			}).then(result => {
				if(result && result.code == 20000){
					this.setState({
						roleList: result.data.roleList
					})
					this.props.form.setFieldsValue({
						userId: id,
						roleIds: result.data.roleIdList
					});
				}
			})
		}
	}
	
	//保存
	save = () => {
		this.props.form.validateFields((err, values) => {
	      if(!err){
	      	sysApi.sysEditUserRoleList(values).then(result => {
	      		if(result && result.code == 20000){
	      			this.props.roleClose(true);
	      		}
	      	})
	      }
	    });
	}
	
	//取消
	cancel = () => {
		this.props.roleClose(false);
	}
	
	render(){
		const { roleList } = this.state;
		const { roleVisible } = this.props;
		const { getFieldDecorator } = this.props.form;
		return(
			<Modal
	          title={"编辑角色"}
	          maskClosable={false}
	          keyboard={false}
	          visible={roleVisible}
	          okText={"保存"}
	          onOk={this.save.bind(this)}
	          cancelText={"取消"}
			  onCancel={this.cancel.bind(this)}>
	          	<Form onSubmit={this.save.bind(this)}>
	          		{getFieldDecorator('userId')(
			            <Input type="hidden"/>
		          	)}
				  	<FormItem>
			          {getFieldDecorator('roleIds')(
			            <RadioGroup>
			            	{
			            		roleList && roleList.length > 0 &&
			            		roleList.map((item, index) => {
			            			return(
			            				<Radio key={index} value={item.roleId}>{item.roleName}</Radio>
			            			)
			            		})
			            	}
			            </RadioGroup>
			          )}
			        </FormItem>
				</Form>
	        </Modal>
		)
	}
}

export default Form.create()(Role);